package org.shagin.jfin.ui;

import java.awt.event.KeyEvent;

import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.KeyStroke;

import org.jdesktop.application.ResourceMap;
import org.shagin.jfin.core.Debug;
import org.shagin.jfin.ui.actions.MainFrameActions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * The Class MainMenu.
 */
public class MainFrameMenu {
    private static final Logger log = LoggerFactory
            .getLogger(MainFrameMenu.class);

    private JMenuBar menuBar;
    private JMainFrame mainFrame;

    /**
     * Instantiates a new main menu.
     * 
     * @param sheetTable the sheet table
     */
    public MainFrameMenu(JMainFrame mainFrame) {
        this.mainFrame = mainFrame;
        buildMenu();
    }

    /**
     * Builds the menu.
     */
    private void buildMenu() {
        menuBar = new JMenuBar();
        JMenu menu;
        // TODO Localize
        menu = createMenu("File", KeyEvent.VK_F);
        menuBar.add(menu);
        menu.add(createMenuItem(MainFrameActions.ACTION_RELOAD));
        menu.add(createMenuItem(MainFrameActions.ACTION_REFRESH));
        menu.add(createMenuItem(MainFrameActions.ACTION_EDIT));
        menu.add(createMenuItem(MainFrameActions.ACTION_SAVE));
    }

    /**
     * Creates the menu.
     * 
     * @param title the title
     * @param mnemonic the mnemonic
     * @return the j menu
     */
    private JMenu createMenu(String title, int mnemonic) {
        JMenu menu = new JMenu(title);
        menu.setMnemonic(mnemonic);
        return menu;
    }

    /**
     * Creates the menu item.
     * 
     * @param actionName the action name
     * @return the j menu item
     */
    private JMenuItem createMenuItem(String actionName) {
        Debug.traceEnter(log, actionName);
        JMenuItem menuItem = new JMenuItem(getAction(actionName));
        ResourceMap resource = mainFrame.getActions().getResourceMap();
        String key = actionName + ".Action." + Action.ACCELERATOR_KEY;
        KeyStroke keyStroke = resource.getKeyStroke(key);
        if (keyStroke != null) {
            menuItem.setAccelerator(keyStroke);
        }
        return menuItem;
    }

    /**
     * Gets the action.
     * 
     * @param name the name
     * @return the action
     */
    private Action getAction(String name) {
        ActionMap map = mainFrame.getActions().getActionMap();
        Action a = map.get(name);
        return a;
    }

    /**
     * Gets the menu bar.
     * 
     * @return the menu bar
     */
    public JMenuBar getMenuBar() {
        return menuBar;
    }
}
